/**
 * 线程间通信 worker
 */
import worker, { ThreadWorkerGlobalScope } from '@ohos.worker'
import hilog from '@ohos.hilog'

let parent: ThreadWorkerGlobalScope = worker.workerPort

let TAG: string = "worker-task"

console.log(TAG, `worker.ts执行---`)


// 处理来自主线程的消息
// 可根据主线程传递来的message信息，进行指定的逻辑处理
parent.onmessage = function (message) {
  hilog.info(0x1002, TAG, "worker thread onmessage:" + JSON.stringify(message))

  if (message.data === "errorTag") {
    throw new Error(`worker内部出现异常`)
    return
  }

  // 发送消息到主线程
  let timer = 0
  let interval = setInterval(() => {
    timer++
    parent.postMessage("message from worker thread! --> " + new Date().getTime())
    if (timer > 500) {
      clearInterval(interval)
      parent.postMessage(`worker线程即将关闭 <----`)
      parent.close()
    }
  }, 5000)

}